import { useAxios } from "@/hooks/useAxios";
import type { IArticle } from "@/types/article";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import type { AxiosError } from "axios";

export const useGetArticle = () => {
  const { http } = useAxios();
  return useQuery<IArticle[], AxiosError>({
    queryKey: ["article"],
    queryFn: async () => {
      const { data } = await http.get("/article");
      return data;
    },
  });
};

export const useGetArticleDetail = (id: string) => {
  const { http } = useAxios();
  return useQuery<IArticle, AxiosError>({
    queryKey: ["article", id],
    queryFn: async () => {
      const { data } = await http.get(`/article/${id}`);
      return data;
    },
  });
};
export const useDelArticle = () => {
  const { http } = useAxios();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (id: string) => {
      return new Promise((resolve) => {
        setTimeout(async () => {
          resolve(await http.delete(`/article/${id}`));
        }, 3000);
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["article"] });
    },
  });
};
export const useAddArticle = () => {
  const { http } = useAxios();
  const navigate = useNavigate();
  return useMutation({
    mutationFn: async (data: IArticle) => {
      return await http.post(`/article`, data);
    },
    onSuccess: () => {
      navigate({ to: "/" });
    },
  });
};
export const useUpdateArticle = () => {
  const { http } = useAxios();
  const navigate = useNavigate();
  return useMutation({
    mutationFn: async (data: IArticle) => {
      return await http.put(`/article/${data.id}`, data);
    },
    onSuccess: () => {
      navigate({ to: "/" });
    },
  });
};
